/*
 * @lc app=leetcode.cn id=993 lang=javascript
 *
 * [993] 二叉树的堂兄弟节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
var isCousins = function(root, x, y) {
    let dep=new Map()
    let par=new Map()
    let dfs=function(node,parNode){
        if(!node)return
        let depth=parNode!=null?dep.get(parNode.val)+1:0;
        dep.set(node.val,depth)
        par.set(node.val,parNode?.val||undefined)
        dfs(node.left,node)
        dfs(node.right,node)
    }
    dfs(root,null)
    return dep.get(x)==dep.get(y)&&par.get(x)!=par.get(y)
};//DFS加Hash,思路是深度递归，同时hash表存储节点值=》节点深度和对应子节点=》父节点，深度递归接收两个参数，当前节点值和父节点，root父节点为null，子节点深度为父节点深度+1,即可
// @lc code=end

var isCousins = function(root, x, y) {
    let queue=[[root]]
    while(queue.length){
        let arr=queue.pop()
        let temp=[]
        let value=[]
        while(arr.length){
            let node=arr.pop()
            if(node.left){temp.push(node.left);value.push(node.left.val)}
            if(node.right){temp.push(node.right);value.push(node.right.val)}
            if(node.left&&node.right){
            if((node.left.val==x&&node.right.val==y)||(node.right.val==x&&node.left.val==y))return false
        }}
        if(value.includes(x)&&value.includes(y))return true
        if(temp.length)queue.push(temp)
    }
    return false
};//BFS层级遍历，分层写法